package me.youline.dataServer.dao.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;




import me.youline.dataServer.dao.UserTokenDAO;
import me.youline.dataServer.entity.UserToken;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component(value = "userTokenCompositeDaoImpl")
public class UserTokenCompositeDaoImpl implements UserTokenDAO {

	private static Logger logger = LoggerFactory
			.getLogger(UserTokenCompositeDaoImpl.class);

	@Autowired
	private UserTokenCacheDAOImpl cacheDao;

	@Autowired
	private UserTokenJdbcDAOImpl jdbcDao;

	@Override
	public void save(UserToken token) {
		jdbcDao.save(token);
		cacheDao.save(token);
		if (logger.isDebugEnabled()) {
			logger.debug("[read_cache_token] current token in cache is{}",
					cacheDao.getUserTokenByTokenStr(token.getToken())
							.getToken());
		}
	}

	@Override
	public boolean deleteUserToken(String token) {
		return jdbcDao.deleteUserToken(token)
				&& cacheDao.deleteUserToken(token);
	}

	@Override
	public boolean updateExpiredAtTime(String token, Date time) {
		return jdbcDao.updateExpiredAtTime(token, time) && cacheDao.updateExpiredAtTime(token, time);
	}

	@Override
	public UserToken getUserTokenByTokenStr(String token) {
		UserToken t = cacheDao.getUserTokenByTokenStr(token);
		return t;
	}

	@Override
	@Transactional
	public void deleteExpiredToken(Date nowTime) {
		jdbcDao.deleteExpiredToken(nowTime);
		cacheDao.deleteExpiredToken(nowTime);
	}

	@Override
	public UserToken getUserTokenByUserName(String userName) {
		UserToken t = jdbcDao.getUserTokenByUserName(userName);
		if (t == null) {
			return null;
		}
		// cacheDao.save(t); 暂时未需要缓存
		return t;
	}

	@Override
	public List<UserToken> loadAllUserToken() {
		for (UserToken t : jdbcDao.loadAllUserToken()) {
			if (logger.isDebugEnabled()) {
				logger.debug("[load_token] load token:{id:{},token:{},expiredAt:{}}", t
						.getUserId(), t.getToken(), DateFormatUtils.format(
						t.getExpiredAt(),
						DateFormatUtils.ISO_DATE_FORMAT.getPattern()));
			}
			cacheDao.getCache().put(t.getToken(), t);
		}
		return Collections.emptyList();
	}

	@Override
	public UserToken getUserTokenTokenByUserId(Long userId) {
		return jdbcDao.getUserTokenTokenByUserId(userId);
	}

}
